package com.quanxiaoha.weblog.common.utils;

import com.quanxiaoha.weblog.common.config.UploadConfig;
import com.quanxiaoha.weblog.common.enums.ResponseCodeEnum;
import com.quanxiaoha.weblog.common.exception.BizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Component
public class MyUtils {
    @Autowired
    private UploadConfig uploadConfig;

    public String uploadImg(MultipartFile fileResource) {
        Long maxSize = uploadConfig.getMaxSize() * 1024 * 1024;
        if (fileResource.getSize() >= maxSize) {
            throw new BizException(ResponseCodeEnum.UPLOAD_FILE_ERROR);
        }
        String path = uploadConfig.getPath();
        File file = new File(path);
        // 判断文件是否存在，不存在先创建
        if (!file.exists()) {
            file.mkdirs();
        }
        // 获取文件名
        String originalFilename = fileResource.getOriginalFilename();
        // 取出文件后缀
        assert originalFilename != null;
        String sufName = originalFilename.substring(originalFilename.lastIndexOf('.'));

        // 使用UUID防止重名，组合后缀获取新的完整文件名
        String fileName = UUID.randomUUID() + sufName;
        try {
            // 上传
            fileResource.transferTo(new File(path, fileName));
            // 返回给前端，自己定义
            return uploadConfig.getUrl() + fileName;
        } catch (Exception e) {
            throw new BizException(ResponseCodeEnum.UPLOAD_FILE_ERROR);
        }
    }
}
